package kz.home.db;

import kz.home.utils.Utils;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordFilter;
import java.util.Vector;
import java.io.UnsupportedEncodingException;

/**
 * <strong>title</strong>
 * <p> describe
 *
 * @author: Danik <br>
 * Date: 21.07.2009  <br>
 * Time: 16:52:46  <br>
 */
public class DBUtils {
    public static final String MOVIES = "MOVIES";
    public static final String CINEMAS = "CINEMAS";
    public static final String CITIES = "CITIES";
    public static final String EVENTS = "EVENTS";
    public static final String TIMES = "TIMES";
    public static final String ROOMS = "ROOMS";
    public static final String TIMETABLE = "TIMETABLE";
    public static final String symbol = "/";

    public static boolean isDBExist() {
        String[] list = RecordStore.listRecordStores();

        for (int i = 0; i < list.length; i++)
            if (EVENTS.equals(list[i])) return true;
        //
        return false;
    }

    public static boolean isNeedUpdate() {
        // проверяем существует ли база
        if(!isDBExist()) return false;
        // проверка есть ли данные за сегодняшний день.
        return isCurrentDay();
    }

    public static void deleteDBEvent() {
        deleteDB(EVENTS);
    }

    public static void deleteDB(String dbName) {
        try {
            RecordStore.deleteRecordStore(dbName);
        } catch (RecordStoreException e) {
           // ignore e.printStackTrace();
        }
    }

    private static boolean isCurrentDay() {
        Vector vector = findInTable(EVENTS, new RecordFilter() {
            public boolean matches(byte[] bytes) {
                return Utils.getCurrentDate().equals(Utils.getID(bytes, symbol));
            }
        });
        return vector.size() > 0;
    }

    private static void save(String tableName, byte[] record) {
        RecordStore store = null;
        try {
            store = RecordStore.openRecordStore(tableName, true);
            store.addRecord(record, 0, record.length);
        } catch (RecordStoreException e) {
            e.printStackTrace();
        } finally {
            closeStore(store);
        }
    }

    public static void saveRoom(String number, String value) {
        try {
            save(ROOMS, (number + symbol + value).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void saveTime(String id, String time, String state) {
        try {
            save(TIMES, (id + symbol + time + symbol + state).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void saveMovies(String id, String movieName, String reference,String state) {
        try {
            save(MOVIES, (id + symbol + movieName + symbol + reference + symbol + state).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void saveCinema(String id, String cinemaName, String cinemaAddress, String state) {
        try {
            save(CINEMAS, (id + symbol + cinemaName + symbol + cinemaAddress + symbol + state).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void saveCity(String id, String cityName, String state, String cinemas, String movies, String times) {
        try {
            save(CITIES, (id + symbol + cityName + symbol + state + symbol + cinemas + symbol + movies + symbol + times).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void saveEvent(String date, String state, String dshort, String dlong, String cit, String cin, String mov, String tim) {
        try {
            save(EVENTS, (date + symbol + state + symbol +dshort + symbol + dlong + symbol + cit + symbol +
                    cin + symbol + mov + symbol + tim).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void saveTimeTable(String date, String cinema, String movie, String room, String time, String priceAdult, String priceStudent, String priceKid) {
        try {
            save(TIMETABLE, (date + symbol + cinema + symbol + movie + symbol + room + symbol + time + symbol + priceAdult + symbol +
                    priceStudent + symbol + priceKid).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    protected void readStore(String DB) {
        RecordStore store = null;

        try {
            store = RecordStore.openRecordStore(DB, false);

            for (int i = 1; i <= store.getNumRecords(); i++) {
                byte[] seed = store.getRecord(i);
                Utils.getValues(seed, symbol);
            }
        } catch (RecordStoreException e) {
            e.printStackTrace();
        } finally {
            closeStore(store);
        }
    }

    public static Vector findInTable(String DB, final String id) {
        RecordStore store = null;
        try {
            store = RecordStore.openRecordStore(DB, false);
            RecordEnumeration recordEnum = store.enumerateRecords(new RecordFilter() {
                public boolean matches(byte[] bytes) {
                    return (Utils.getID(bytes, symbol).equals(id));
                }
            }, null, false);

            if (recordEnum.hasNextElement()) {
                byte[] seed = recordEnum.nextRecord();
                return Utils.getValues(seed, symbol);
            }
        } catch (RecordStoreException e) {
            e.printStackTrace();
        } finally {
            closeStore(store);
        }
        return new Vector();
    }

    protected static Vector findInTable(String DB, RecordFilter filter) {
        Vector result = new Vector();
        RecordStore store = null;
        try {
            store = RecordStore.openRecordStore(DB, false);
            RecordEnumeration recordEnum = store.enumerateRecords(filter, null, false);

            while (recordEnum.hasNextElement()) {
                byte[] seed = recordEnum.nextRecord();
                result.addElement(Utils.getValues(seed, symbol));
            }
        } catch (RecordStoreException e) {
            e.printStackTrace();
        } finally {
            if (store != null) {
                try {
                    store.closeRecordStore();
                } catch (RecordStoreException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static Vector getFromDB(String DB) {
        Vector result = new Vector();
        RecordStore store = null;

        try {
            store = RecordStore.openRecordStore(DB, false);
            for (int i = 1; i <= store.getNumRecords(); i++) {
                byte[] seed = store.getRecord(i);
                result.addElement(Utils.getValues(seed, symbol));
            }
        } catch (RecordStoreException e) {
            e.printStackTrace();
        } finally {
            closeStore(store);
        }
        return result;
    }

    private static void closeStore(RecordStore store) {
        if (store != null) {
            try {
                store.closeRecordStore();
            } catch (RecordStoreException e) {
                e.printStackTrace();
            }
        }
    }
}